package com.cowmooed.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cowmooed.dto.GenerationRecordsDTO;
import com.cowmooed.entity.GenerationRecords;
import com.cowmooed.dto.GenerationRecordsPageQueryDTO;
import com.cowmooed.entity.PageResult;
import com.cowmooed.exception.GlobalExceptionHandler;
import com.cowmooed.mapper.GenerationRecordsMapper;
import com.cowmooed.service.GenerationRecordsService;
import com.cowmooed.utils.BaseContextUtil;
import com.cowmooed.vo.GenerationRecordsQueryVO;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;


import java.util.ArrayList;
import java.util.List;

/**
 * 生成记录服务实现类
 */
@Service
public class GenerationRecordsServiceImpl extends ServiceImpl<GenerationRecordsMapper, GenerationRecords> implements GenerationRecordsService {
    private static final Logger log = LoggerFactory.getLogger(GenerationRecordsServiceImpl.class);
    /**
     * 分页查询当前登录用户的模型记录
     * @param generationRecordsPageQueryDTO 分页查询参数
     * @return 分页查询结果
     */
    @Override
    public PageResult pageQueryUserRecords(GenerationRecordsPageQueryDTO generationRecordsPageQueryDTO) {
        // 1. 获取参数
        Integer pageNum = generationRecordsPageQueryDTO.getPage();
        Integer pageSize = generationRecordsPageQueryDTO.getPageSize();

        // 2. 获取当前登录用户的ID
        Long userId = BaseContextUtil.getCurrentId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }
        
        // 3. 使用PageHelper进行分页
        PageHelper.startPage(pageNum, pageSize);
        
        // 4. 查询当前用户isDisplay为true(1)的记录
        Page<GenerationRecords> page = (Page<GenerationRecords>) lambdaQuery()
                .eq(GenerationRecords::getUserId, userId)
                .eq(GenerationRecords::getIsDisplay, true)
                .orderByDesc(GenerationRecords::getUpdatedTime)
                .list();
        
        // 5. 将查询结果转换为GenerationRecordsQueryVO列表
        List<GenerationRecordsQueryVO> resultList = new ArrayList<>();
        for (GenerationRecords record : page.getResult()) {
            GenerationRecordsQueryVO vo = GenerationRecordsQueryVO.builder()
                    .id(record.getId())
                    .generationMethod(record.getGenerationMethod())
                    .taskId(record.getTaskId())
                    .requestId(record.getRequestId())
                    .prompt(record.getPrompt())
                    .imageUrl(record.getImageUrl())
                    .model3dUrl(record.getModel3dUrl())
                    .status(record.getStatus())
                    .build();
            resultList.add(vo);
        }
        
        // 6. 构造并返回PageResult对象
        return new PageResult(page.getTotal(), resultList);
    }

    @Override
    public void updateRecordByUserIdAndTaskIdAndRequestId(GenerationRecordsDTO generationRecordsDTO) {
        // 1. 获取当前登录用户的ID
        Long userId = BaseContextUtil.getCurrentId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 2. 构建更新条件和更新字段
        lambdaUpdate()
                .eq(GenerationRecords::getUserId, userId)
                .eq(GenerationRecords::getRequestId, generationRecordsDTO.getRequestId())
                // 设置需要更新的字段
                .set(generationRecordsDTO.getModel3dUrl() != null, GenerationRecords::getModel3dUrl, generationRecordsDTO.getModel3dUrl())
                .set(generationRecordsDTO.getStatus() != null, GenerationRecords::getStatus, generationRecordsDTO.getStatus())
                .set(generationRecordsDTO.getIsDisplay() != null, GenerationRecords::getIsDisplay, generationRecordsDTO.getIsDisplay())
                // 更新修改时间
                .set(GenerationRecords::getUpdatedTime, java.time.LocalDateTime.now())
                // 执行更新
                .update();
    }

    @Override
    public void batchUpdateRecordsByUserIdAndTaskIdAndRequestId(List<GenerationRecordsDTO> generationRecordsDTOList) {
        // 1. 验证参数
        if (generationRecordsDTOList == null || generationRecordsDTOList.isEmpty()) {
            throw new GlobalExceptionHandler.BusinessException("参数错误");
        }

        // 2. 获取当前登录用户的ID
        Long userId = BaseContextUtil.getCurrentId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 3. 遍历列表，对每个对象进行更新操作
        for (GenerationRecordsDTO dto : generationRecordsDTOList) {
            try {
                // 对每个对象调用单个更新方法
                updateRecordByUserIdAndTaskIdAndRequestId(dto);
            } catch (Exception e) {
                // 记录异常但继续处理下一个对象
                log.error("更新记录失败: " + e.getMessage());
            }
        }
    }

    @Override
    public void batchDeleteRecordsByIds(List<Long> ids) {
        // 1. 验证参数
        if (ids == null || ids.isEmpty()) {
            throw new GlobalExceptionHandler.BusinessException("请选择删除目标");
        }

        // 2. 获取当前登录用户的ID
        Long userId = BaseContextUtil.getCurrentId();
        if (userId == null) {
            throw new RuntimeException("用户未登录");
        }

        // 3. 根据ID列表和当前用户ID进行删除操作
        // 确保只能删除自己的记录
        lambdaUpdate()
                .in(GenerationRecords::getId, ids)
                .eq(GenerationRecords::getUserId, userId)
                .remove();
    }
}